package com.ilxqx.framework.system.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ilxqx.framework.security.config.SecurityConfigProperties;
import com.ilxqx.framework.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author venus
 * 响应工具类
 */
@Slf4j
public final class ResponseUtils {

    /**
     * html格式
     */
    private static final String HTML = "text/html";

    /**
     * json处理对象
     */
    private static ObjectMapper objectMapper;

    /**
     * 安全配置对象
     */
    private static SecurityConfigProperties securityConfigProperties;

    /**
     * 初始化objectMapper对象
     */
    private static void init () {
        if (objectMapper == null) {
            objectMapper = SpringUtils.getBean(ObjectMapper.class);
        }
        if (securityConfigProperties == null) {
            securityConfigProperties = SpringUtils.getBean(SecurityConfigProperties.class);
        }
    }

    /**
     * 将对象转为json字符串
     * @param object 对象
     */
    public static void response (Object object, HttpServletRequest request, HttpServletResponse response, int status) throws IOException {
        // 初始化ObjectMapper，如果不存在的话
        init();
        Assert.notNull(object, "响应数据不能为空");
        // 获取Response对象
        Assert.notNull(response, "响应对象Response不存在");
        if (StringUtils.containsIgnoreCase(request.getHeader(HttpHeaders.ACCEPT), HTML)) {
            // 是页面访问，直接重定向
            response.sendRedirect(securityConfigProperties.getLoginPage());
            return;
        }
        // 设置响应内容格式
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(status);
        try {
            response.getWriter().print(objectMapper.writeValueAsString(object));
        } catch (IOException e) {
            // 处理错误
            log.error("响应信息出现错误：{}", e);
            throw new SecurityException("响应出现错误");
        }
    }

    /**
     * 响应结果
     * @param object 数据
     * @param request 请求对象
     * @param response 响应对象
     * @throws IOException IO异常
     */
    public static void response(Object object, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResponseUtils.response(object, request, response, HttpStatus.OK.value());
    }

}
